<template>
    <div class="meeting-approval-manage">
        <!-- 面包屑和标题 -->
        <el-breadcrumb separator="/" class="mb-2">
            <el-breadcrumb-item>会议管理</el-breadcrumb-item>
            <el-breadcrumb-item>会议审批管理</el-breadcrumb-item>
        </el-breadcrumb>
        <div class="page-title">会议审批管理</div>

        <!-- 查询区 -->
        <div class="search-area">
            <el-input v-model="query.Subject" placeholder="请输入会议主题" clearable style="width: 220px;" />
            <el-input v-model="query.MeetingRoomName" placeholder="请输入会议室名称" clearable style="width: 220px;" />
            <el-date-picker v-model="query.MeetingDate" type="date" placeholder="请选择会议日期" format="YYYY-MM-DD"
                value-format="YYYY-MM-DD" clearable style="width: 220px;" />
            <el-button type="primary" @click="onSearch">查询</el-button>
            <el-button @click="onReset">重置</el-button>
        </div>

        <!-- 审批表格 -->
        <el-table :data="tableData" border stripe style="width: 100%">
            <el-table-column prop="MeetingApprovalId" label="ID" width="60" />
            <el-table-column prop="MeetingRoomName" label="会议室" min-width="120" />
            <el-table-column prop="Subject" label="会议主题" min-width="150" />
            <el-table-column prop="HostName" label="主持人" min-width="100" />
            <el-table-column prop="StartTime" label="开始时间" min-width="180">
                <template #default="scope">
                    {{ formatDate(scope.row.StartTime) }}
                </template>
            </el-table-column>
            <el-table-column prop="EndTime" label="结束时间" min-width="180">
                <template #default="scope">
                    {{ formatDate(scope.row.EndTime) }}
                </template>
            </el-table-column>
            <el-table-column prop="CreateTime" label="提交时间" min-width="180">
                <template #default="scope">
                    {{ formatDate(scope.row.MeetingDate) }}
                </template>
            </el-table-column>
            <el-table-column prop="Status" label="审批状态" width="100">
                <template #default="scope">
                    <el-tag :type="getApprovalStateTagType(scope.row.Status)">
                        {{ getApprovalStateText(scope.row.Status) }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="200" fixed="right">
                <template #default="scope">
                    <el-button size="small" type="primary" plain @click="onApprove(scope.row)">
                        <el-icon>
                            <Check />
                        </el-icon>审批
                    </el-button>
                    <el-button size="small" type="info" plain @click="onView(scope.row)">
                        <el-icon>
                            <View />
                        </el-icon>详情
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <CustomPagination class="mt-2" :currentPage="pageIndex" :pageSize="pageSize" :totalCount="pageInfo.totalCount"
            :totalPage="pageInfo.totalPage" @size-change="onPageSizeChange" @current-change="onCurrentPageChange" />

        <!-- 合并后的审批详情弹窗 -->
        <el-dialog v-model="approvalDialog.visible" :title="approvalDialog.isViewOnly ? '会议详情' : '会议审批'" width="800px">
            <div class="approval-detail" v-if="approvalDialog.meeting">
                <div class="section-title">基本信息</div>
                <el-row>
                    <el-col :span="8">
                        <div class="detail-item"><span class="item-label">会议名称：</span>{{ approvalDialog.meeting.Subject
                        }}
                        </div>
                    </el-col>
                    <el-col :span="8">
                        <div class="detail-item"><span class="item-label">会议时间：</span>
                            {{ formatMeetingTime(approvalDialog.meeting.MeetingDate, approvalDialog.meeting.StartTime,
                                approvalDialog.meeting.EndTime) }}
                        </div>
                    </el-col>
                    <el-col :span="8">
                        <div class="detail-item"><span class="item-label">会议地点：</span>{{
                            approvalDialog.meeting.MeetingRoomName }}
                        </div>
                    </el-col>
                </el-row>
                <el-row class="mt-2">
                    <el-col :span="8">
                        <div class="detail-item"><span class="item-label">主持人：</span>{{ approvalDialog.meeting.HostName
                            }}</div>
                    </el-col>
                    <el-col :span="16">
                        <div class="detail-item"><span class="item-label">提交时间：</span>{{
                            formatDate(approvalDialog.meeting.MeetingDate) }}</div>
                    </el-col>
                </el-row>
                <el-row class="mt-2">
                    <el-col :span="24">
                        <div class="detail-item">
                            <span class="item-label">参会人员：</span>
                            <el-tag v-for="(name, idx) in parseParticipants(approvalDialog.meeting.Participants)"
                                :key="idx" class="mr-1">{{ name }}</el-tag>
                        </div>
                    </el-col>
                </el-row>
                <el-row class="mt-2">
                    <el-col :span="24">
                        <div class="detail-item"><span class="item-label">会议内容：</span>{{ approvalDialog.meeting.Content
                        }}
                        </div>
                    </el-col>
                </el-row>

                <!-- 查看模式：显示当前审批状态和意见 -->
                <template v-if="approvalDialog.isViewOnly">
                    <div class="section-title mt-3">审批信息</div>
                    <el-row class="mt-2">
                        <el-col :span="8">
                            <div class="detail-item"><span class="item-label">审批状态：</span>
                                <el-tag :type="getApprovalStateTagType(approvalDialog.meeting.Status)">
                                    {{ getApprovalStateText(approvalDialog.meeting.Status) }}
                                </el-tag>
                            </div>
                        </el-col>
                        <el-col :span="16">
                            <div class="detail-item"><span class="item-label">审批意见：</span>{{
                                approvalDialog.meeting.ApprovalThing || '暂无' }}</div>
                        </el-col>
                    </el-row>
                </template>

                <!-- 审批模式：显示审批表单 -->
                <template v-else>
                    <div class="section-title mt-3">审批信息</div>
                    <el-form :model="approvalForm" label-width="100px">
                        <el-form-item label="审批结果:" prop="Result" required>
                            <el-radio-group v-model="approvalForm.Result">
                                <el-radio :label="'通过'">通过</el-radio>
                                <el-radio :label="'拒绝'">拒绝</el-radio>
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item label="审批意见:" prop="ApprovalThing">
                            <el-input v-model="approvalForm.ApprovalThing" type="textarea" :rows="3"
                                placeholder="请输入审批意见" maxlength="20" show-word-limit />
                        </el-form-item>
                    </el-form>
                </template>
            </div>
            <template #footer>
                <el-button @click="approvalDialog.visible = false">{{ approvalDialog.isViewOnly ? '关闭' : '取消'
                }}</el-button>
                <el-button v-if="!approvalDialog.isViewOnly" type="primary" @click="onSubmitApproval">确定</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Check, View } from '@element-plus/icons-vue' // 引入需要的图标
import CustomPagination from '@/components/CustomPagination.vue'
import moment from 'moment' // 导入 moment 用于日期格式化
import { useStore } from '@/stores/userInfo'
import {
    getMeetingApprovalList,
    submitMeetingApproval,
    type MeetingApprovalItem,
    type MeetingApprovalListParams,
    type SubmitApprovalParams
} from '@/api/meetingApproval' // 导入会议审批API

// 获取用户信息
const store = useStore()

// 查询参数
const query = reactive<MeetingApprovalListParams>({
    Subject: '',
    MeetingRoomName: '',
    MeetingDate: '',
    UserId: store.userinfo?.userid || '2',
    pageIndex: 1,
    pageSize: 10
})

const tableData = ref<MeetingApprovalItem[]>([])

const pageIndex = ref(1)
const pageSize = ref(10)
const pageInfo = reactive({
    totalCount: 0,
    totalPage: 1
})

// 审批弹窗状态
const approvalDialog = reactive({
    visible: false,
    meeting: null as MeetingApprovalItem | null,
    isViewOnly: false,
})

// 审批表单
const approvalForm = reactive({
    MeetingApprovalId: 0,
    Result: '通过', // 默认通过
    ApprovalThing: '',
    UserId: store.userinfo?.userid || '2',
})

// 解析参与人字符串
const parseParticipants = (participantsStr: string) => {
    return participantsStr ? participantsStr.split(',').filter(p => p.trim() !== '') : []
}

// 格式化会议时间
const formatMeetingTime = (date: string | undefined, startTime: string | undefined, endTime: string | undefined) => {
    if (!date || !startTime || !endTime) return '时间未设置';

    try {
        const formattedDate = moment(date).format('YYYY-MM-DD');
        const formattedStartTime = moment(startTime).format('HH:mm');
        const formattedEndTime = moment(endTime).format('HH:mm');
        return `${formattedDate} ${formattedStartTime} - ${formattedEndTime}`;
    } catch (error) {
        console.error('格式化会议时间出错:', error);
        return `${date || ''} ${startTime || ''} - ${endTime || ''}`;
    }
}

// 格式化日期时间
const formatDate = (dateString: string | undefined) => {
    if (!dateString) return ''
    return moment(dateString).format('YYYY-MM-DD HH:mm:ss')
}

// 获取审批状态标签类型
const getApprovalStateTagType = (Status: any) => {
    // 将状态值转换为数字进行比较
    const statusNum = Number(Status);
    console.log('状态标签类型，原始值:', Status, '转换后:', statusNum);

    switch (statusNum) {
        case 0: return 'info' // 待审批
        case 1: return 'warning' // 进行中
        case 2: return 'success' // 已结束
        case 3: return 'danger' // 已取消
        case 4: return 'info' // 待开始
        case 5: return 'success' // 已解决
        default: return 'info'
    }
}

// 获取审批状态文本
const getApprovalStateText = (Status: any) => {
    // 将状态值转换为数字进行比较
    const statusNum = Number(Status);
    console.log('状态文本，原始值:', Status, '转换后:', statusNum);

    switch (statusNum) {
        case 0: return '待审批'
        case 1: return '进行中'
        case 2: return '已结束'
        case 3: return '已取消'
        case 4: return '待开始'
        case 5: return '已解决'
        default:
            console.log('未知状态:', Status);
            return '未知'
    }
}

// 获取会议审批列表
const fetchMeetingApprovalList = async () => {
    try {
        const response = await getMeetingApprovalList({
            pageIndex: query.pageIndex,
            pageSize: query.pageSize,
            Subject: query.Subject,
            MeetingRoomName: query.MeetingRoomName,
            MeetingDate: query.MeetingDate,
            UserId: query.UserId
        })

        console.log('会议审批列表响应数据:', response)

        // 安全地访问响应数据，使用类型断言避免TypeScript错误
        const responseObj = response as any;

        if (responseObj && typeof responseObj === 'object') {
            // 尝试从不同的可能的响应结构中获取数据
            const responseData = responseObj.Data || (responseObj.data && responseObj.data.Data) || responseObj.data;

            if (responseData && Array.isArray(responseData.Data)) {
                tableData.value = responseData.Data;
                // 添加日志输出检查数据结构
                console.log('会议审批列表数据结构:', tableData.value);
                if (tableData.value.length > 0) {
                    console.log('第一条数据完整信息:', JSON.stringify(tableData.value[0]));
                    console.log('第一条数据Status类型:', typeof tableData.value[0]?.Status);
                    console.log('第一条数据Status值:', tableData.value[0]?.Status);
                }
                if (tableData.value.length > 1) {
                    console.log('第二条数据完整信息:', JSON.stringify(tableData.value[1]));
                    console.log('第二条数据Status类型:', typeof tableData.value[1]?.Status);
                    console.log('第二条数据Status值:', tableData.value[1]?.Status);
                }

                pageInfo.totalCount = responseData.TotalCount || 0;
                pageInfo.totalPage = responseData.TotalPage || 1;
            } else {
                console.warn('响应数据结构不符合预期:', responseData);
                tableData.value = [];
                pageInfo.totalCount = 0;
                pageInfo.totalPage = 1;
            }
        } else {
            console.warn('获取会议审批列表响应数据结构异常:', response);
            tableData.value = [];
            pageInfo.totalCount = 0;
            pageInfo.totalPage = 1;
        }
    } catch (error) {
        console.error('获取会议审批列表失败:', error);
        tableData.value = [];
        pageInfo.totalCount = 0;
        pageInfo.totalPage = 1;
        ElMessage.error('获取会议审批列表失败');
    }
}

// 查询
const onSearch = () => {
    query.pageIndex = 1
    fetchMeetingApprovalList()
}

// 重置
const onReset = () => {
    query.Subject = ''
    query.MeetingRoomName = ''
    query.MeetingDate = ''
    query.pageIndex = 1
    fetchMeetingApprovalList()
}

// 查看详情
const onView = async (row: MeetingApprovalItem) => {
    try {
        // 使用合并后的弹窗显示详情
        approvalDialog.meeting = { ...row };
        // 不显示审批表单，只查看详情
        approvalDialog.isViewOnly = true;
        approvalDialog.visible = true;
    } catch (error) {
        console.error('获取会议审批详情失败:', error);
        ElMessage.warning('获取详细信息失败，请重试');
    }
}

// 审批会议
const onApprove = (row: MeetingApprovalItem) => {
    approvalDialog.meeting = { ...row };
    approvalForm.MeetingApprovalId = row.MeetingApprovalId;
    approvalForm.Result = '通过'; // 默认通过
    approvalForm.ApprovalThing = '';
    // 显示审批表单
    approvalDialog.isViewOnly = false;
    approvalDialog.visible = true;
}

// 提交审批
const onSubmitApproval = async () => {
    try {
        // 表单校验
        if (!approvalForm.Result) {
            ElMessage.warning('请选择审批结果');
            return;
        }
        // 将审批结果转换为后端期望的格式
        let resultValue = '';
        if (approvalForm.Result === '通过') {
            resultValue = '通过';  // 直接使用"通过"字符串
        } else if (approvalForm.Result === '拒绝') {
            resultValue = '驳回';  // 使用"驳回"字符串而不是"拒绝"
        }

        // 显示加载中提示
        ElMessage({
            message: '正在提交审批...',
            type: 'info'
        });

        const response = await submitMeetingApproval({
            MeetingApprovalId: approvalForm.MeetingApprovalId,
            Result: resultValue,
            ApprovalThing: approvalForm.ApprovalThing,
            UserId: approvalForm.UserId
        });

        // 使用类型断言安全处理响应
        const responseObj = response as any;

        if (responseObj && (responseObj.IsSuc || responseObj.IsSucc)) {
            ElMessage.success('审批' + resultValue);
            approvalDialog.visible = false;
            fetchMeetingApprovalList(); // 重新加载列表
        } else {
            console.warn('提交审批响应异常:', responseObj);
            ElMessage.error(responseObj?.Msg || '提交审批失败');
        }
    } catch (error: any) {
        console.error('提交审批失败:', error);
        ElMessage.error(error.message || '提交审批失败');
    }
}

// 页面大小改变
const onPageSizeChange = (size: number) => {
    query.pageSize = size
    fetchMeetingApprovalList()
}

// 当前页改变
const onCurrentPageChange = (current: number) => {
    query.pageIndex = current
    fetchMeetingApprovalList()
}

onMounted(() => {
    console.log('===== 会议审批页面已挂载 =====');
    console.log('状态映射表:');
    console.log('0 => ' + getApprovalStateText(0));
    console.log('1 => ' + getApprovalStateText(1));
    console.log('2 => ' + getApprovalStateText(2));
    console.log('3 => ' + getApprovalStateText(3));
    console.log('4 => ' + getApprovalStateText(4));
    console.log('5 => ' + getApprovalStateText(5));
    console.log('"已解决" 对应的状态值应该是 5');
    fetchMeetingApprovalList();
    console.log('===== 会议审批页面数据加载完成 =====');
})
</script>

<style scoped>
.meeting-approval-manage {
    padding: 24px;
}

.page-title {
    font-size: 22px;
    font-weight: bold;
    margin-bottom: 18px;
}

.search-area {
    margin-bottom: 18px;
    display: flex;
    align-items: center;
    gap: 12px;
}

/* 详情弹窗样式 */
.approval-detail {
    padding: 10px;
}

.section-title {
    font-size: 16px;
    font-weight: bold;
    margin: 10px 0;
    padding-bottom: 5px;
    border-bottom: 1px solid #ebeef5;
}

.detail-item {
    display: flex;
    margin-bottom: 10px;
}

.item-label {
    font-weight: bold;
    width: 120px;
    color: #606266;
}

.mr-1 {
    margin-right: 4px;
}

.mt-2 {
    margin-top: 8px;
}

.mt-3 {
    margin-top: 12px;
}
</style>